import { Injectable } from '@nestjs/common';
import { join } from 'path';
import { writeFile } from 'fs/promises';
import { HttpException, HttpStatus } from '@nestjs/common';
@Injectable()
export class ApConfigService {
   
  
  async exportConfig(){
    await new Promise((resolve,reject)=>{
      setTimeout(()=>{
        resolve(true)
      },2000)
    })
    return {
      code:200,
      data:{
        addr:"http://192.168.5.74:3001/public/README.md",
      }
    }
  }

   async exportApConfig(){
    await new Promise((resolve,reject)=>{
      setTimeout(()=>{
        resolve(true)
      },2000)
    })
    return {
      code:200,
      data:{
        addr:"http://192.168.5.74:3001/public/README.md",
      }
    }
   }

   async exportCpConfig(){
    await new Promise((resolve,reject)=>{
      setTimeout(()=>{
        resolve(true)
      },2000)
    })
    return {
      code:200,
      data:{
        addr:"http://192.168.5.74:3001/public/config.toml",
      }
    }
   }

   async saveConfig(body: {
    fileData: string,
    ip?: string
  }){
    try {
      if (!body.fileData) {
        throw new Error('缺少必要的文件数据');
      }
      const filePath = join(process.cwd(), 'public', 'README.md');
      await writeFile(filePath, body.fileData);
      return {
        code: 200,
        data: {
          status: true,
          message: '配置保存成功'
        }
      };
    } catch (error) {
      throw new HttpException(
        `配置保存失败: ${error.message}`,
        HttpStatus.BAD_REQUEST
      );
    }
   }


  async importConfig(body: {
    filedata: Express.Multer.File | string | any,
    filename: string
  }) {
    try {
      if (!body.filedata || !body.filename) {
        throw new Error('缺少必要的文件数据或文件名');
      }
      let content: string | Buffer;
      if (body.filedata instanceof Buffer) {
        content = body.filedata;
      } else if (typeof body.filedata === 'string') {
        content = body.filedata;
      } else if (body.filedata.buffer) {
        content = body.filedata.buffer;
      } else {
        throw new Error('文件数据格式不正确');
      }
      const filePath = join(process.cwd(), 'public', body.filename);
      await writeFile(filePath, content);   
      return {
        code: 200,
        message: '配置导入成功'
      };
    } catch (error) {
      console.error('Import error:', {
        error,
        receivedData: {
          hasFiledata: !!body.filedata,
          filedataType: typeof body.filedata,
          isBuffer: body.filedata instanceof Buffer,
          hasBuffer: !!body.filedata?.buffer,
          filename: body.filename
        }
      });
      throw new HttpException(
        `配置导入失败: ${error.message}`, 
        HttpStatus.BAD_REQUEST
      );
    }
  }
 
}
